/**
 * 验证用户是否登录
 */

var userModel = require('../models/user');

var jwt = require('jwt-simple');
var  crypto = require('crypto');
var tokenConfig=require('../utils/config').tokenConfig;
module.exports={
  createToken:function (req) {
    var token=jwt.encode({
      iss:req.body.uname,
      exp:tokenConfig.expires
    },tokenConfig.jwtTokenSecret);
    return token;
  },
  ValidateToken:function (req,res,callback) {
    var token = (req.body && req.body.access_token) || (req.query && req.query.access_token) || req.headers['x-access-token'];
    if (token) {
      try {
        var decoded = jwt.decode(token, tokenConfig.jwtTokenSecret);
        if (decoded.exp <= Date.now()) { //token过期
          res.json({
            code:301,
            msg:'你未登录，请登录',
            obj:null
          })
        }else{ //已登录
          userModel.checkUser(decoded.iss,function(data) {
            callback(data[0]);
          })
        }
      } catch (err) {
        res.json({
          code:301,
          msg:'你未登录，请登录',
          obj:null
        })
      }
    } else {
      //不存在token 用户未登录
      res.json({
        code:301,
        msg:'你未登录，请登录',
        obj:null
      })
    }
  }
}
